<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量调整服务用户价格"
    width="400px"
    @close="resetForm"
  >
    <el-alert title="增量，正数为加价，负数为降价" type="success" />
    <el-form
      ref="serviceForm"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="mt-3"
    >
      <el-form-item label="服务类型" prop="serviceType">
        <el-select
          v-model="form.serviceType"
          placeholder="请选择"
          filterable
          clearable
          class="w-full"
        >
          <el-option
            v-for="item in serviceTypes"
            :key="item.standardCode"
            :label="item.displayName"
            :value="item.standardCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="增量" prop="delta">
        <el-input-number v-model="form.delta" class="!w-full" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="success" :loading @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, type PropType } from "vue";
import { adjustUserCustomPricesByService } from "@/api/adminPriceApi";
import { message } from "@/utils/message";

interface ServiceItem {
  standardCode: string;
  displayName: string;
}

const dialogVisible = ref(false);
const loading = ref(false);
defineProps({
  serviceTypes: {
    type: Array as PropType<ServiceItem[]>,
    default: () => []
  }
});
const emits = defineEmits(["refresh"]);
const form = reactive({
  delta: 0,
  serviceType: ""
});
// 基础校验规则
const rules = {
  delta: [{ required: true, message: "请输入增量", trigger: "blur" }],
  serviceType: [
    { required: true, message: "请选择服务类型", trigger: "change" }
  ]
};

const serviceForm = ref(null);
// 重置表单
const resetForm = () => {
  serviceForm.value?.resetFields();
};

const handleConfirm = () => {
  serviceForm.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true;
        const { serviceType, delta } = form;
        const { message: text } = await adjustUserCustomPricesByService(
          serviceType,
          {
            delta
          }
        );
        message(text || "设置成功", { type: "success" });
        emits("refresh");
        dialogVisible.value = false;
      } catch (error) {
        console.log(error);
      } finally {
        loading.value = false;
      }
    }
  });
};
const open = () => {
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
